package cn.wolfcode.wms.controller;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.qo.EmployeeQueryObject;
import cn.wolfcode.wms.service.IDepartmentService;
import cn.wolfcode.wms.service.IEmployeeService;
import cn.wolfcode.wms.service.IRoleService;
import cn.wolfcode.wms.util.RequiredPermission;
import cn.wolfcode.wms.vo.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    @RequiredPermission("员工列表")
    public String list(@ModelAttribute("qo") EmployeeQueryObject qo, Map map) {
        map.put("departments", departmentService.listAll());
        map.put("pageResult", employeeService.query(qo));
        return "employee/list";
    }

    @RequestMapping("/input")
    @RequiredPermission("编辑员工")
    public String input(Long id, Map map) {
        map.put("departments", departmentService.listAll());
        map.put("roles", roleService.listAll());
        if (id != null) {
            map.put("employee", employeeService.getById(id));
        }
        return "employee/input";
    }

    @RequestMapping("/saveOrUpdate")
    @RequiredPermission("更新或新增员工")
    public String saveOrUpdate(Employee employee, Long[] ids) {
        employeeService.saveOrUpdate(employee, ids);
        return "redirect:/employee/list.do";
    }

    @RequestMapping("/delete")
    @RequiredPermission("删除员工")
    public String delete(Long id) {
        employeeService.deleteById(id);
        return "redirect:/employee/list.do";
    }


    @RequestMapping("/batchDelete")
    @RequiredPermission("批量删除员工")
    @ResponseBody
    public JSONResult batchDelete(@RequestParam("ids[]") Long[] ids) {
        try {
            employeeService.batchDelete(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return JSONResult.mark(e.getMessage());
        }
        return JSONResult.success("批量删除成功！");
    }

    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        return "success!";
    }
}
